package org.u2ml.stack.web;

import org.mortbay.jetty.Connector;
import org.mortbay.jetty.Server;
import org.mortbay.jetty.nio.SelectChannelConnector;
import org.mortbay.jetty.servlet.Context;
import org.mortbay.jetty.webapp.WebAppContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.context.WebApplicationContext;
import org.u2ml.stack.web.rest.XRestApplication;
import org.u2ml.stack.web.spring.XContextLoaderListener;
import org.u2ml.stack.web.spring.XWebApplicationContext;


public class WebServer {
	private final Logger logger = LoggerFactory.getLogger(WebServer.class); 
	
	private Server server;
	private XContextLoaderListener contextLoaderListener;
	
	public WebServer(int port) {
		server = new Server();
		SelectChannelConnector connector = new SelectChannelConnector();
		connector.setPort(port);
		server.setConnectors(new Connector[] { connector });
	}

	public WebServer join() throws InterruptedException {
		server.join();
		return this;
	}
	
	public WebServer start() throws Exception {
		logger.info("starting jetty...");
		server.start();
		return this;
	}
	
	public WebServer stop() throws Exception {
		server.stop();
		return this;
	}

	@SuppressWarnings("unchecked")
	public WebServer addServerContext(String contextPath) {
		logger.info("adding server context at {}", contextPath);
		
		Context serverContext = new Context();
		serverContext.setContextPath(contextPath);
		serverContext.setDisplayName("U2ML");
		serverContext.getInitParams().put(
				"org.restlet.application", XRestApplication.class.getName());
		serverContext.getInitParams().put(
				"contextClass", XWebApplicationContext.class.getName());
		contextLoaderListener = new XContextLoaderListener();
		serverContext.addEventListener(contextLoaderListener);
		serverContext.addServlet(PushServlet.class, "/*");
		server.addHandler(serverContext);
		
		return this;
	}
	
	public WebServer addUIContext(String uiRoot, String uiPath) {
		logger.info("adding ui context for {} at {}", uiRoot, uiPath);
		WebAppContext uiContext = new WebAppContext();
		uiContext.setContextPath(uiPath);
		uiContext.setWar(uiRoot);
		server.addHandler(uiContext);
		
		return this;
	}
	
	public WebApplicationContext getApplicationContext() {
		if (contextLoaderListener != null) {
			return contextLoaderListener.getContext();
		} else {
			return null;
		}
	}
	
}
